import React, { useCallback, useState } from "react";
import { Layout, Menu, theme, Button } from "antd";
import * as Icon from "@ant-design/icons";
import { newRoutes } from "@/router";
import { Link, useResolvedPath, useLocation } from "react-router-dom";
import collapsedIcon from "@/assets/collapse-icon.svg";

const { Sider } = Layout;
const { SubMenu } = Menu;

export const SiderMenu = () => {
  const {
    token: { colorBgContainer },
  } = theme.useToken();

  const formatMenus = (arr) => {
    if (!arr || arr.length === 0 || !Array.isArray(arr)) {
      return [];
    }

    return arr.map((item) => {
      return {
        label: item.title,
        link: item.path,
        key: item.path,
        icon: item.icon ? React.createElement(Icon[item.icon]) : "",
        children: item.children ? formatMenus(item.children) : null,
      };
    });
  };

  const menus = formatMenus([...newRoutes].filter((m) => !m.hiddenInMenu));

  const renderMenu = useCallback((menus_params) => {
    return menus_params.map((menu) =>
      menu.children ? (
        <SubMenu title={menu.label} icon={menu.icon} key={menu.link}>
          {renderMenu(menu.children)}
        </SubMenu>
      ) : (
        <Menu.Item key={menu.link}>
          <Link to={menu.link}>{menu.label}</Link>
        </Menu.Item>
      )
    );
  }, []);

  const selectKeys = useLocation()?.pathname;
  console.log(selectKeys);

  const [collapsed, setCollapsed] = useState(false);

  return (
    <Sider trigger={null} width={200} collapsible collapsed={collapsed}>
      <img
        className={`trigger-button  ${collapsed ? "transition-style" : ""}`}
        style={{ right: "-32px" }}
        src={collapsedIcon}
        onClick={() => setCollapsed(!collapsed)}
      />
      <Menu
        style={{ background: "#E8E8ED", height: "100%" }}
        mode="inline"
        defaultSelectedKeys={[selectKeys]}
        defaultOpenKeys={["/userCenter"]}
      >
        {renderMenu(menus)}
      </Menu>
    </Sider>
  );
};
